package com.mrchip.service_intent;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button mbtStartService;
    private Button mbtStopService;
    private Button mbtBindService;
    private Button mbtUnBindService;
    private Button mbtGetInfo;
    private MyService.ServiceBinder serviceBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("Activity", "Service is connected.");
            serviceBinder = (MyService.ServiceBinder) iBinder;
            serviceBinder.startTask();
            serviceBinder.getTaskProcess();
            mbtGetInfo.setEnabled(true);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("Activity", "Service is disconnected.");
            mbtGetInfo.setEnabled(false);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mbtStartService = findViewById(R.id.btStartService);
        mbtStopService = findViewById(R.id.btStopService);
        mbtBindService = findViewById(R.id.btBindService);
        mbtUnBindService = findViewById(R.id.btUnbindService);
        mbtGetInfo = findViewById(R.id.btGetInfo);
        mbtStartService.setOnClickListener(this);
        mbtStopService.setOnClickListener(this);
        mbtBindService.setOnClickListener(this);
        mbtUnBindService.setOnClickListener(this);
        mbtGetInfo.setOnClickListener(this);
        mbtGetInfo.setOnClickListener(this);
        mbtGetInfo.setEnabled(false);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btStartService:
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent);
                break;
            case R.id.btStopService:
                Intent stopIntent = new Intent(this, MyService.class);
                stopService(stopIntent);
                break;
            case R.id.btBindService:
                Intent bindIntent = new Intent(this, MyService.class);
                bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
                break;
            case R.id.btUnbindService:
                unbindService(serviceConnection);
                break;
            case R.id.btGetInfo:
                serviceBinder.getTaskProcess();
                break;
        }
    }
}

